package club.dataresources.util;

import club.dataresources.config.LogoConfig;
import com.google.zxing.common.BitMatrix;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;

/**
 * @author tao
 */
public class MatrixToImageWriter {
    /**
     * 用于设置图案的颜色
     */
    private static final int BLACK = 0xFF000000;
    /**
     * 用于背景色
     */
    private static final int WHITE = 0xFFFFFFFF;

    /**
     * @param bitMatrix
     * @param format
     * @param outfile
     * @throws Exception
     */
    public static void writeToFile(BitMatrix bitMatrix, String format, File outfile) throws Exception {
        BufferedImage image = toBufferedImage(bitMatrix);
        //设置logo图标
        LogoConfig logoConfig = new LogoConfig();
        image = logoConfig.logoMatrix(image);
        if (!ImageIO.write(image, format, outfile)) {
            throw new IOException("Could not write an image of format " + format + " to " + outfile);
        } else {
            System.out.println("write to file successfully");
        }
    }

    /**
     * @param matrix
     * @param format
     * @param stream
     * @throws Exception
     */
    public static void writeToStream(BitMatrix matrix, String format, OutputStream stream) throws Exception {
        BufferedImage image = toBufferedImage(matrix);
        //设置logo图标
        LogoConfig logoConfig = new LogoConfig();
        image = logoConfig.logoMatrix(image);
        if (!ImageIO.write(image, format, stream)) {
            throw new IOException("Could not write an image of format " + format);
        } else {
            System.out.println("write to file successfully");
        }
    }

    /**
     * @param bitMatrix
     * @return
     */
    private static BufferedImage toBufferedImage(BitMatrix bitMatrix) {
        int width = bitMatrix.getWidth();
        int height = bitMatrix.getHeight();
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                image.setRGB(x, y, (bitMatrix.get(x, y) ? BLACK : WHITE));
            }
        }
        return image;
    }
}
